<template>
  <Dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :isModal="false"
    :fullscreen="false"
    @close="close"
    width="800px"
    style="border-radius: 10px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3)"
  >
    <div class="output-container max-h-80 overflow-auto">
      <pre v-for="(text, index) in messageList" :key="index">{{ text }}</pre>
    </div>
  </Dialog>
</template>
<script setup name="ExecResultTip" lang="ts">
import { getAccessToken } from '@/utils/auth'
import { useWebSocket, UseWebSocketReturn } from '@vueuse/core'
import { useCache, CACHE_KEY } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const message = useMessage() // 消息弹窗
const dialogTitle = ref('')

const dialogVisible = ref(false)
const socketType = ref('')
/** 发起 WebSocket 连接 */
const socketObject = ref<UseWebSocketReturn<any>>()
const sendText = ref() // 发送内容

const messageList = ref<any[]>([])
const receivingList = ref<any>({})
watch(
  () => socketObject.value?.data,
  (data) => {
    if (!data) {
      return
    }
    const receiveData = unref(data)
    try {
      // 1. 收到心跳
      if (receiveData === 'pong') {
        return
      }

      // 2.1 解析 type 消息类型
      const jsonMessage = JSON.parse(receiveData)
      const type = jsonMessage.type
      const content = JSON.parse(jsonMessage.content)
      if (!type) {
        message.error('未知的消息类型：' + data)
        return
      }
      if (type != socketType.value) return
      if (content.status == 'error') {
        messageList.value.push('未知错误：' + content.message)
        return
      }
      if (content.message.startsWith('\r')) {
        const newContent = content.message.slice(1)
        if (messageList.value.length > 0) {
          messageList.value[messageList.value.length - 1] = newContent
        } else {
          messageList.value.push(newContent)
        }
      } else {
        messageList.value.push(content.message)
      }
    } catch (error) {
      message.error('处理消息发生异常：' + data)
      console.error(error)
    }
  }
)
const handlerSend = () => {
  const jsonMessage = JSON.stringify({
    type: socketType.value,
    content: JSON.stringify(sendText.value)
  })
  // 发送消息
  socketObject.value?.send(jsonMessage)
  sendText.value = []
}

/** 打开弹窗 */
const open = async (param, type) => {
  if (type == 'server-init') dialogTitle.value = '服务器初始化'
  if (type == 'customer-init') dialogTitle.value = '客户初始化'
  if (type == 'customer-upgrade') dialogTitle.value = '客户升级'
  socketType.value = type
  dialogVisible.value = true
  messageList.value = []
  receivingList.value = {}
  socketObject.value = useWebSocket(
    wsCache.get(CACHE_KEY.SERVER_WS_URL) + '?token=' + getAccessToken(),
    {
      autoReconnect: false,
      heartbeat: false
    }
  )
  sendText.value = param
  handlerSend()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 关闭弹窗 */
const close = async () => {
  if (unref(socketObject.value?.status) === 'OPEN') socketObject.value?.close()
  dialogVisible.value = false
}
</script>
<style scoped>
.console-output {
  font-family: monospace; /* 使用等宽字体，保持格式一致 */
  background-color: #282c34; /* 类似终端背景色 */
  color: #ffffff; /* 白色文字 */
  padding: 20px;
  border-radius: 8px;
  max-height: 400px; /* 限制高度 */
  overflow-y: auto; /* 自动滚动 */
}

.output-container {
  margin-top: 10px;
}

.output-container pre {
  margin: 0; /* 移除默认间距 */
  white-space: pre-wrap; /* 允许换行 */
  word-break: break-all; /* 防止长单词超出容器 */
}
</style>
